const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const User = require('../db/user');
const wechatService = require('../services/wechatService');

// JWT密钥
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

// 手机号验证函数
function validatePhoneNumber(phoneNumber) {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phoneNumber);
}

// 一键登录/注册
router.post('/login', async (req, res) => {
  try {
    const { phoneNumber, verificationCode } = req.body;
  
    // 验证手机号格式
    if (!phoneNumber || !validatePhoneNumber(phoneNumber)) {
      return res.status(400).json({
      success: false, 
        message: '手机号格式不正确'
    });
    }

    // 查找用户
    let user = await User.findOne({ phoneNumber });
    
    // 如果有验证码，进行验证码验证（只允许已注册用户）
    if (verificationCode) {
      if (!user) {
        return res.status(400).json({
          success: false,
          message: '该手机号未注册，请先进行注册'
        });
      }
      
      // 这里应该验证验证码，暂时跳过验证
      console.log(`验证码登录: ${phoneNumber}, 验证码: ${verificationCode}`);
    } else {
      // 一键登录：用户不存在则自动注册
      if (!user) {
        user = new User({
          phoneNumber,
          isRegistered: true,
          registrationTime: new Date()
        });
        await user.save();
        console.log(`新用户注册: ${phoneNumber}`);
      }
    }

    // 更新登录信息
    user.lastLoginTime = new Date();
    user.loginCount += 1;
    await user.save();

    // 生成JWT token
    const token = jwt.sign(
      { 
        userId: user._id, 
        phoneNumber: user.phoneNumber 
      },
      JWT_SECRET,
      { expiresIn: '7d' }
    );

    // 判断是否是首次注册
    const isNewUser = user.loginCount === 0;
    
    res.json({
      success: true,
      message: isNewUser ? '注册成功，已自动登录' : '验证码登录成功',
      token,
      user: {
        id: user._id,
        phoneNumber: user.phoneNumber,
        isRegistered: user.isRegistered,
        registrationTime: user.registrationTime,
        lastLoginTime: user.lastLoginTime,
        loginCount: user.loginCount
      }
    });

  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，请稍后重试'
    });
  }
});

// 发送验证码
router.post('/send-code', async (req, res) => {
  try {
    const { phoneNumber } = req.body;
    
    // 验证手机号格式
    if (!phoneNumber || !validatePhoneNumber(phoneNumber)) {
      return res.status(400).json({
        success: false,
        message: '手机号格式不正确'
      });
    }

    // 生成随机6位数验证码
    const verificationCode = Math.floor(100000 + Math.random() * 900000).toString();
    
    // 这里应该集成短信服务发送验证码
    // 暂时返回成功，实际项目中需要集成短信API
    console.log(`发送验证码到: ${phoneNumber}, 验证码: ${verificationCode}`);
    
    res.json({
      success: true,
      message: '验证码已发送',
      code: verificationCode // 随机6位数验证码
    });

  } catch (error) {
    console.error('发送验证码错误:', error);
    res.status(500).json({
      success: false,
      message: '发送验证码失败，请稍后重试'
    });
  }
});

// 获取已注册手机号列表（用于切换）
router.get('/phone-list', async (req, res) => {
  try {
    // 只获取已注册用户的手机号
    const users = await User.find({ isRegistered: true })
      .select('phoneNumber registrationTime lastLoginTime')
      .sort({ lastLoginTime: -1 }); // 按最后登录时间排序
    
    const phoneList = users.map(user => ({
      phoneNumber: user.phoneNumber,
      registrationTime: user.registrationTime,
      lastLoginTime: user.lastLoginTime
    }));
    
    res.json({
      success: true,
      data: phoneList
    });
  } catch (error) {
    console.error('获取手机号列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取手机号列表失败'
    });
  }
});

// 注册接口
router.post('/register', async (req, res) => {
  try {
    const { phoneNumber, verificationCode } = req.body;
    
    // 验证手机号格式
    if (!phoneNumber || !validatePhoneNumber(phoneNumber)) {
      return res.status(400).json({
        success: false,
        message: '手机号格式不正确'
      });
    }

    // 验证验证码
    if (!verificationCode || verificationCode.length !== 6) {
      return res.status(400).json({
        success: false,
        message: '验证码格式不正确'
      });
    }

    // 检查用户是否已存在
    let user = await User.findOne({ phoneNumber });
    if (user) {
      return res.status(400).json({
        success: false,
        message: '该手机号已注册'
      });
    }

    // 这里应该验证验证码，暂时跳过验证
    console.log(`注册用户: ${phoneNumber}, 验证码: ${verificationCode}`);

    // 创建新用户
    user = new User({
      phoneNumber,
      isRegistered: true,
      registrationTime: new Date()
    });
    await user.save();
    console.log(`新用户注册成功: ${phoneNumber}`);

    // 生成JWT token
    const token = jwt.sign(
      { 
        userId: user._id, 
        phoneNumber: user.phoneNumber 
      },
      JWT_SECRET,
      { expiresIn: '7d' }
    );

    res.json({
      success: true,
      message: '注册成功',
      token,
      user: {
        id: user._id,
        phoneNumber: user.phoneNumber,
        isRegistered: user.isRegistered,
        registrationTime: user.registrationTime,
        lastLoginTime: user.lastLoginTime,
        loginCount: user.loginCount
      }
    });

  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({
      success: false,
      message: '注册失败，请稍后重试'
    });
  }
});

// 获取用户信息
router.get('/profile', async (req, res) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({
        success: false,
        message: '未提供认证token'
      });
    }

    const decoded = jwt.verify(token, JWT_SECRET);
    const user = await User.findById(decoded.userId);
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      user: {
        id: user._id,
        phoneNumber: user.phoneNumber,
        isRegistered: user.isRegistered,
        registrationTime: user.registrationTime,
        lastLoginTime: user.lastLoginTime,
        loginCount: user.loginCount,
        status: user.status
      }
    });

  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(401).json({
      success: false,
      message: 'token无效或已过期'
    });
  }
});

// 获取所有用户列表（管理员功能）
router.get('/list', async (req, res) => {
  try {
    const users = await User.find({}, { 
      phoneNumber: 1, 
      isRegistered: 1, 
      registrationTime: 1, 
      lastLoginTime: 1, 
      loginCount: 1, 
      status: 1 
    }).sort({ createdAt: -1 });

    res.json({
      success: true,
      users,
      total: users.length
    });

  } catch (error) {
    console.error('获取用户列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 删除用户（管理员功能）
router.delete('/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const user = await User.findByIdAndDelete(userId);
    
    if (!user) {
      return res.status(404).json({
      success: false,
      message: '用户不存在'
      });
    }

    res.json({
      success: true,
      message: '用户删除成功'
    });

  } catch (error) {
    console.error('删除用户错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// ==================== 微信登录相关接口 ====================

/**
 * 获取微信登录二维码URL
 * GET /users/wechat/qr-url
 */
router.get('/wechat/qr-url', (req, res) => {
  try {
    const state = Math.random().toString(36).substring(2, 15);
    const qrUrl = wechatService.generateQRCodeUrl(state);
    
    res.json({
      success: true,
      qrUrl,
      state
    });
  } catch (error) {
    console.error('生成微信二维码URL失败:', error);
    res.status(500).json({
      success: false,
      message: '生成二维码失败'
    });
  }
});

/**
 * 微信登录回调处理
 * POST /users/wechat/callback
 */
router.post('/wechat/callback', async (req, res) => {
  try {
    const { code } = req.body;
    
    if (!code) {
      return res.status(400).json({
        success: false,
        message: '授权码不能为空'
      });
    }

    // 1. 完成微信登录流程
    const wechatUserInfo = await wechatService.completeLogin(code);
    
    if (!wechatUserInfo.openid) {
      return res.status(400).json({
        success: false,
        message: '获取微信用户信息失败'
      });
    }

    // 2. 查找或创建用户
    let user = await User.findOne({ wechatOpenId: wechatUserInfo.openid });
    
    if (!user) {
      // 新用户，创建账号
      user = new User({
        phoneNumber: `wx_${wechatUserInfo.openid.slice(-8)}`, // 生成虚拟手机号
        isRegistered: true,
        registrationTime: new Date(),
        wechatOpenId: wechatUserInfo.openid,
        wechatUnionId: wechatUserInfo.unionid || null,
        wechatNickname: wechatUserInfo.nickname || '微信用户',
        wechatAvatar: wechatUserInfo.headimgurl || '',
        wechatAccessToken: wechatUserInfo.access_token,
        wechatRefreshToken: wechatUserInfo.refresh_token,
        wechatTokenExpiresAt: new Date(Date.now() + wechatUserInfo.expires_in * 1000),
        loginType: 'wechat'
      });
      await user.save();
      console.log(`新微信用户注册成功: ${wechatUserInfo.openid}`);
    } else {
      // 更新登录信息和微信信息
      user.lastLoginTime = new Date();
      user.loginCount += 1;
      user.wechatNickname = wechatUserInfo.nickname || user.wechatNickname;
      user.wechatAvatar = wechatUserInfo.headimgurl || user.wechatAvatar;
      user.wechatAccessToken = wechatUserInfo.access_token;
      user.wechatRefreshToken = wechatUserInfo.refresh_token;
      user.wechatTokenExpiresAt = new Date(Date.now() + wechatUserInfo.expires_in * 1000);
      await user.save();
      console.log(`微信用户登录: ${wechatUserInfo.openid}`);
    }

    // 3. 生成JWT token
    const token = jwt.sign(
      { 
        userId: user._id, 
        phoneNumber: user.phoneNumber,
        loginType: 'wechat'
      },
      JWT_SECRET,
      { expiresIn: '7d' }
    );

    res.json({
      success: true,
      message: '微信登录成功',
      token,
      user: {
        id: user._id,
        phoneNumber: user.phoneNumber,
        isRegistered: user.isRegistered,
        registrationTime: user.registrationTime,
        lastLoginTime: user.lastLoginTime,
        loginCount: user.loginCount,
        loginType: user.loginType,
        wechatNickname: user.wechatNickname,
        wechatAvatar: user.wechatAvatar
      }
    });

  } catch (error) {
    console.error('微信登录回调处理失败:', error);
    
    // 处理微信API错误
    if (error.message.includes('微信API错误')) {
      const errcode = error.message.match(/微信API错误: (\d+)/)?.[1];
      const errorMsg = wechatService.getErrorMessage(errcode);
      
      return res.status(400).json({
        success: false,
        message: `微信登录失败: ${errorMsg}`
      });
    }
    
    res.status(500).json({
      success: false,
      message: '微信登录失败，请稍后重试'
    });
  }
});

/**
 * 刷新微信access_token
 * POST /users/wechat/refresh-token
 */
router.post('/wechat/refresh-token', async (req, res) => {
  try {
    const { userId } = req.body;
    
    if (!userId) {
      return res.status(400).json({
        success: false,
        message: '用户ID不能为空'
      });
    }

    // 查找用户
    const user = await User.findById(userId);
    if (!user || !user.wechatRefreshToken) {
      return res.status(400).json({
        success: false,
        message: '用户不存在或没有微信刷新令牌'
      });
    }

    // 检查token是否过期
    if (user.wechatTokenExpiresAt && user.wechatTokenExpiresAt > new Date()) {
      return res.json({
        success: true,
        message: 'Token未过期，无需刷新',
        access_token: user.wechatAccessToken
      });
    }

    // 刷新access_token
    const tokenInfo = await wechatService.refreshAccessToken(user.wechatRefreshToken);
    
    // 更新用户信息
    user.wechatAccessToken = tokenInfo.access_token;
    user.wechatRefreshToken = tokenInfo.refresh_token;
    user.wechatTokenExpiresAt = new Date(Date.now() + tokenInfo.expires_in * 1000);
    await user.save();

    res.json({
      success: true,
      message: 'Token刷新成功',
      access_token: tokenInfo.access_token,
      expires_in: tokenInfo.expires_in
    });

  } catch (error) {
    console.error('刷新微信token失败:', error);
    res.status(500).json({
      success: false,
      message: '刷新Token失败，请重新登录'
    });
  }
});

/**
 * 获取微信用户信息
 * GET /users/wechat/user-info/:userId
 */
router.get('/wechat/user-info/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    
    // 查找用户
    const user = await User.findById(userId);
    if (!user || !user.wechatOpenId) {
      return res.status(400).json({
        success: false,
        message: '用户不存在或不是微信用户'
      });
    }

    // 检查access_token是否有效
    const isValid = await wechatService.checkAccessToken(user.wechatAccessToken, user.wechatOpenId);
    
    if (!isValid) {
      // Token无效，尝试刷新
      try {
        const tokenInfo = await wechatService.refreshAccessToken(user.wechatRefreshToken);
        user.wechatAccessToken = tokenInfo.access_token;
        user.wechatRefreshToken = tokenInfo.refresh_token;
        user.wechatTokenExpiresAt = new Date(Date.now() + tokenInfo.expires_in * 1000);
        await user.save();
      } catch (refreshError) {
        return res.status(401).json({
          success: false,
          message: '微信授权已过期，请重新登录'
        });
      }
    }

    // 获取最新的用户信息
    const wechatUserInfo = await wechatService.getUserInfo(user.wechatAccessToken, user.wechatOpenId);
    
    // 更新用户信息
    user.wechatNickname = wechatUserInfo.nickname;
    user.wechatAvatar = wechatUserInfo.headimgurl;
    await user.save();

    res.json({
      success: true,
      userInfo: {
        openid: wechatUserInfo.openid,
        nickname: wechatUserInfo.nickname,
        avatar: wechatUserInfo.headimgurl,
        sex: wechatUserInfo.sex,
        province: wechatUserInfo.province,
        city: wechatUserInfo.city,
        country: wechatUserInfo.country
      }
    });

  } catch (error) {
    console.error('获取微信用户信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户信息失败'
    });
  }
});

// ==================== 人脸识别登录接口 ====================

/**
 * 人脸识别登录接口
 * POST /users/face-login
 */
router.post('/face-login', async (req, res) => {
  try {
    const { faceImage, timestamp } = req.body;
    
    if (!faceImage) {
      return res.status(400).json({
        success: false,
        message: '人脸图像数据不能为空'
      });
    }

    // 这里应该集成人脸识别服务
    // 暂时模拟人脸识别过程
    console.log('收到人脸识别登录请求:', {
      timestamp,
      imageSize: faceImage.length
    });

    // 模拟人脸识别验证（实际项目中需要集成专业的人脸识别API）
    // 这里简单模拟：如果图像数据长度大于1000，认为识别成功
    const isFaceRecognized = faceImage.length > 1000;
    
    if (!isFaceRecognized) {
      return res.status(400).json({
        success: false,
        message: '人脸识别失败，请确保人脸清晰可见'
      });
    }

    // 模拟找到用户（实际项目中需要根据人脸特征查找用户）
    // 这里创建一个临时用户或查找现有用户
    let user = await User.findOne({ loginType: 'face' });
    
    if (!user) {
      // 创建新的人脸识别用户
      user = new User({
        phoneNumber: `face_${Date.now()}`, // 生成临时手机号
        isRegistered: true,
        registrationTime: new Date(),
        loginType: 'face',
        // 可以添加人脸特征数据字段
        faceFeatures: faceImage.substring(0, 100) // 简单存储部分图像数据作为特征
      });
      await user.save();
      console.log('新人脸识别用户注册成功');
    } else {
      // 更新登录信息
      user.lastLoginTime = new Date();
      user.loginCount += 1;
      await user.save();
      console.log('人脸识别用户登录成功');
    }

    // 生成JWT token
    const token = jwt.sign(
      { 
        userId: user._id, 
        phoneNumber: user.phoneNumber,
        loginType: 'face'
      },
      JWT_SECRET,
      { expiresIn: '7d' }
    );

    res.json({
      success: true,
      message: '人脸识别登录成功',
      token,
      user: {
        id: user._id,
        phoneNumber: user.phoneNumber,
        isRegistered: user.isRegistered,
        registrationTime: user.registrationTime,
        lastLoginTime: user.lastLoginTime,
        loginCount: user.loginCount,
        loginType: user.loginType
      }
    });

  } catch (error) {
    console.error('人脸识别登录错误:', error);
    res.status(500).json({
      success: false,
      message: '人脸识别登录失败，请稍后重试'
    });
  }
});

// ==================== 临时兼容接口 ====================

/**
 * 临时微信登录接口（兼容旧版本）
 * POST /users/wechat-login
 */
router.post('/wechat-login', async (req, res) => {
  try {
    const { wechatUserInfo } = req.body;
    
    if (!wechatUserInfo || !wechatUserInfo.openid) {
      return res.status(400).json({
        success: false,
        message: '微信用户信息不完整'
      });
    }

    // 查找是否已有该微信用户
    let user = await User.findOne({ wechatOpenId: wechatUserInfo.openid });
    
    if (!user) {
      // 新微信用户，创建账号
      user = new User({
        phoneNumber: `wx_${wechatUserInfo.openid.slice(-8)}`, // 生成虚拟手机号
        isRegistered: true,
        registrationTime: new Date(),
        wechatOpenId: wechatUserInfo.openid,
        wechatUnionId: wechatUserInfo.unionid || null,
        wechatNickname: wechatUserInfo.nickname || '微信用户',
        wechatAvatar: wechatUserInfo.avatar || '',
        loginType: 'wechat'
      });
      await user.save();
      console.log(`新微信用户注册成功: ${wechatUserInfo.openid}`);
    } else {
      // 更新登录信息
      user.lastLoginTime = new Date();
      user.loginCount += 1;
      if (wechatUserInfo.nickname) user.wechatNickname = wechatUserInfo.nickname;
      if (wechatUserInfo.avatar) user.wechatAvatar = wechatUserInfo.avatar;
      await user.save();
      console.log(`微信用户登录: ${wechatUserInfo.openid}`);
    }

    // 生成JWT token
    const token = jwt.sign(
      { 
        userId: user._id, 
        phoneNumber: user.phoneNumber,
        loginType: 'wechat'
      },
      JWT_SECRET,
      { expiresIn: '7d' }
    );

    res.json({
      success: true,
      message: '微信登录成功',
      token,
      user: {
        id: user._id,
        phoneNumber: user.phoneNumber,
        isRegistered: user.isRegistered,
        registrationTime: user.registrationTime,
        lastLoginTime: user.lastLoginTime,
        loginCount: user.loginCount,
        loginType: user.loginType,
        wechatNickname: user.wechatNickname,
        wechatAvatar: user.wechatAvatar
      }
    });

  } catch (error) {
    console.error('微信登录错误:', error);
    res.status(500).json({
      success: false,
      message: '微信登录失败，请稍后重试'
    });
  }
});

module.exports = router;
